package thinking.in.spring.ioc.overview.dependency.injection;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.Environment;
import thinking.in.spring.ioc.overview.domain.User;
import thinking.in.spring.ioc.overview.repository.UserRepository;

/**
 * 依赖注入示例
 *
 * @author Ringo
 * @date 2021/8/22 12:04
 */
public class DependencyInjectionDemo {

    public static void main(String[] args) {
        String configLocation = "classpath:/META-INF/dependency-injection-context.xml";
//        BeanFactory beanFactory = new ClassPathXmlApplicationContext(configLocation);
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(configLocation);
        // 依赖注入
        UserRepository userRepository = applicationContext.getBean(UserRepository.class);

        System.out.println(applicationContext);
        System.out.println(userRepository.getBeanFactory());
        // 这个等式为什么不成立？
        System.out.println(userRepository.getBeanFactory() == applicationContext);

        // 这个等式成立
        System.out.println(userRepository.getBeanFactory() == applicationContext.getAutowireCapableBeanFactory());


//        System.out.println(userRepository.getBeanFactory());
//        System.out.println(userRepository.getObjectFactory().getObject());
//        System.out.println(applicationContext == userRepository.getObjectFactory().getObject());

        // 依赖查找
//        System.out.println(applicationContext.getBean(BeanFactory.class));

//        Environment environment = applicationContext.getBean(Environment.class);
//        System.out.println("获取 Environment 类型的 Bean: " + environment);
    }

    private static void lookupInType(BeanFactory beanFactory) {
        UserRepository userRepository = beanFactory.getBean(UserRepository.class);
        System.out.println(userRepository);
        System.out.println(userRepository.getBeanFactory());
        System.out.println(userRepository.getObjectFactory().getObject());
    }

}
